package com.wz.jiangsu.main.problem;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

/**
 * @program: wz
 * @author: wangzhou
 * @create: 2024-04-25 11.52
 * @description:
 **/
public class HappyNumber {

    static Map<Integer,Integer> map = new HashMap<>();
    static boolean flag1;
    public static void main(String[] args) {
        int num = 28;
        Boolean happyNum = isHappyNum2(num);
        if (happyNum) {
            System.out.println("快乐数:" + num);
        }else{
            System.out.println("不是快乐数");
        }
    }
    private static Boolean isHappyNum(int num) {

        boolean flag ;
        ArrayList<Integer> list = new ArrayList<>();
        list = addList(list,num);

        int sum = 0;
        for (Integer integer : list) {
            sum += (int) Math.pow(integer, 2);
        }
        if (sum == 1){
          flag = true;
        }else {
            if (map.containsKey(num)) {
                flag = false;
            } else {
                map.put(num,sum);
                flag = isHappyNum(sum);
            }
        }
        return flag;
    }

    private static Boolean isHappyNum2(int num) {

        ArrayList<Integer> list = new ArrayList<>();
        list = addList(list,num);

        int sum = 0;
        for (Integer integer : list) {
            sum += (int) Math.pow(integer, 2);
        }
        if (sum == 1){
            flag1 = true;
        }else {
            if (map.containsKey(num)) {
                flag1 = false;
            } else {
                map.put(num,sum);
                isHappyNum2(sum);
            }
        }
        return flag1;
    }
    private static ArrayList<Integer> addList(ArrayList<Integer> list, int num) {
        if(num >=10) {
             int addNum = num %10;
             list.add(addNum);
             addList(list,num /10);
        } else {
            list.add(num);
        }
        return  list;
    }
}


